package com.monika.main.security.handler;

import com.monika.main.system.constant.CacheConstant;
import com.monika.main.system.constant.Constant;
import com.monika.main.system.domain.AjaxResult;
import com.monika.main.system.domain.entity.LoginUser;
import com.monika.main.system.exception.BaseException;
import com.monika.main.system.util.RedisCache;
import com.monika.main.system.util.ServletUtil;
import com.monika.main.system.util.TokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * Author whh
 * Date 2023/04/22/ 17:50
 * <p></p>
 */
@Component
public class PrimalLogoutHandler implements LogoutHandler {
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUser loginUser = TokenUtil.getLoginUser(request);

        if(Objects.isNull(loginUser)){
            ServletUtil.renderString(response, AjaxResult.fail("身份令牌无效，退出失败").ajaxResultJson());
            throw new BaseException("身份令牌无效，退出失败");
        }
        String token = loginUser.getToken();
        RedisCache.delete(CacheConstant.LOGIN_TOKEN_KEY+token);
    }
}
